package org.easydev.base.webbase.config;

import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.easydev.base.webbase.bo.JsonEntity;
import org.easydev.base.webbase.constants.ApiConst;
import org.easydev.base.webbase.exception.BizException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.Optional;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(BizException.class)
    public JsonEntity<String> handleBizException(BizException be, HttpServletResponse response) {
        response.setStatus(be.getHttpStatus().value());
        log.error(be.getMessage(),be);
        String errorCode = Optional.ofNullable(be.getErrorCode()).orElse(ApiConst.RESPONSE_CODE_ERROR);
        return JsonEntity.customError(errorCode,be.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public JsonEntity<String> handleGeneralException(Exception ex, HttpServletResponse response) {
        log.error(ex.getMessage(),ex);
        int status = response.getStatus();
        if(status == HttpStatus.OK.value()) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        String errorMsg = "An unexpected error occurred";
        if(ex instanceof MaxUploadSizeExceededException) {
            errorMsg = "文件大小超过限制";
        }
        return JsonEntity.error(errorMsg);
    }

}
